﻿using LmgCMS.Model;
using LmgCMS.Service;
using Microsoft.AspNetCore.Mvc;

namespace LmgCMS.Areas.API.Controllers {
    /// <summary>
    /// 角色权限
    /// </summary>
    public class RoleAuthorizeController : BaseController
    {
        private readonly IMenuService _menuDal;
        private readonly IMenuElementService _menuElementDal;
        private readonly IRelevanceService _relevanceService;
        public RoleAuthorizeController(IMenuService menuService,
            IMenuElementService menuElementService,
            IRelevanceService relevanceService)
        {
            _menuDal = menuService;
            _menuElementDal = menuElementService;
            _relevanceService = relevanceService;
        }
        [HttpGet]
        public ActionResult GetPermissionTree(string roleId)
        {
            var moduledata = _menuDal.FindAll();
            var buttondata = _menuElementDal.FindAll();

            List<string> moduleIds = new List<string>();
            List<string> buttonIds = new List<string>();

            if (!string.IsNullOrEmpty(roleId))
            {
                moduleIds = _relevanceService.FindAll("[Key] ='"+ Define.ROLEMODULE + "' AND FirstId = '"+ roleId + "'").Select(u => u.SecondId).ToList();
                buttonIds = _relevanceService.FindAll("[Key] ='" + Define.ROLEELEMENT + "' AND FirstId = '" + roleId + "'").Select(u => u.SecondId).ToList();
            }
            var treeList = new List<TreeViewModel>();
            foreach (Menu item in moduledata)
            {
                TreeViewModel tree = new TreeViewModel();
                tree.id = item.ID;
                tree.text = item.Name;
                tree.title = item.Name;
                tree.value = item.Code;
                tree.parentId = item.ParentID;
                tree.isexpand = false;
                tree.complete = true;
                tree.showcheck = true;
                tree.checkstate = moduleIds.Contains(item.ID) ? 1 : 0;
                tree.hasChildren = true;
                tree.img = item.Icon == "" ? "fa fa-bars" : item.Icon;
                treeList.Add(tree);
            }
            foreach (MenuElement item in buttondata)
            {
                TreeViewModel tree = new TreeViewModel();
                tree.id = item.ID;
                tree.text = item.Name;
                tree.title = item.Name;
                tree.value = item.DomId;
                tree.parentId = item.ModuleId;
                tree.isexpand = false;
                tree.complete = true;
                tree.showcheck = true;
                tree.checkstate = buttonIds.Contains(item.ID) ? 1 : 0;
                tree.hasChildren = false;
                tree.img = item.Icon == "" ? "fa fa-file-text-o" : item.Icon;
                treeList.Add(tree);
            }
            return Content(treeList.TreeViewJson());
        }
    }
}
